package org.hfy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hfy.common.ApiResponse;
import org.hfy.dto.OptionDTO;
import org.hfy.dto.OutsourcingQueryDTO;
import org.hfy.entity.Outsourcing;
import org.hfy.entity.Quotation;
import org.hfy.service.InboundService;
import org.hfy.service.OutsourcingService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 外发加工控制器
 * 
 * @author hfy
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/outsourcing")
@RequiredArgsConstructor
@Validated
public class OutsourcingController {

    private final OutsourcingService outsourcingService;
    private final InboundService inboundService;

    /**
     * 分页查询外发加工列表
     */
    @GetMapping
    public ApiResponse<IPage<Outsourcing>> getOutsourcingPage(OutsourcingQueryDTO query) {
        IPage<Outsourcing> page = outsourcingService.getOutsourcingPage(query);
        return ApiResponse.success(page);
    }

    /**
     * 根据ID查询外发加工详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Outsourcing> getOutsourcingById(@PathVariable Long id) {
        Outsourcing outsourcing = outsourcingService.getOutsourcingWithDetailsById(id);
        return ApiResponse.success(outsourcing);
    }

    /**
     * 创建外发单
     */
    @PostMapping
    public ApiResponse<Outsourcing> createOutsourcing(@Valid @RequestBody Outsourcing outsourcing) {
        Outsourcing result = outsourcingService.createOutsourcing(outsourcing);
        return ApiResponse.success("外发单创建成功", result);
    }

    /**
     * 删除外发单
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteOutsourcing(@PathVariable Long id) {
        boolean result = outsourcingService.deleteOutsourcing(id);
        if (result) {
            return ApiResponse.success("外发单删除成功");
        } else {
            return ApiResponse.error("外发单删除失败");
        }
    }

    /**
     * 更新外发状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<String> updateOutsourcingStatus(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        String status = (String) request.get("status");
        LocalDate actualReturnDate = null;
        
        if (request.containsKey("actualReturnDate") && request.get("actualReturnDate") != null) {
            actualReturnDate = LocalDate.parse((String) request.get("actualReturnDate"));
        }
        
        boolean result = outsourcingService.updateOutsourcingStatus(id, status, actualReturnDate);
        if (result) {
            return ApiResponse.success("外发状态更新成功");
        } else {
            return ApiResponse.error("外发状态更新失败");
        }
    }

    /**
     * 获取供应商选项列表
     */
    @GetMapping("/supplier-options")
    public ApiResponse<List<OptionDTO>> getSupplierOptions() {
        List<OptionDTO> options = outsourcingService.getSupplierOptions();
        return ApiResponse.success(options);
    }

    /**
     * 获取可用于外发加工的报价记录列表
     * 包括状态为"合同审核通过"和"外发加工中"的报价单
     */
    @GetMapping("/available-quotations")
    public ApiResponse<List<Quotation>> getAvailableQuotationsForOutsourcing() {
        List<Quotation> quotations = outsourcingService.getAvailableQuotationsForOutsourcing();
        return ApiResponse.success(quotations);
    }

    /**
     * 获取可入库的外发单列表
     * 状态为"已回厂"且未完全入库的外发单可以进行入库操作
     */
    @GetMapping("/available-for-inbound")
    public ApiResponse<IPage<Outsourcing>> getAvailableOutsourcingForInbound(OutsourcingQueryDTO query) {
        // 设置查询条件：状态为"已回厂"
        if (query == null) {
            query = new OutsourcingQueryDTO();
        }
        query.setStatus("已回厂");
        
        IPage<Outsourcing> page = outsourcingService.getOutsourcingPage(query);
        
        // 过滤掉已完全入库的外发单
        List<Outsourcing> filteredRecords = page.getRecords().stream()
                .filter(outsourcing -> {
                    // 获取该外发单的已入库总数量
                    Integer totalInboundQuantity = inboundService.getTotalInboundQuantityByOutsourcingId(outsourcing.getId());
                    // 如果已入库数量小于外发数量，则还可以继续入库
                    return totalInboundQuantity < outsourcing.getQuantity();
                })
                .collect(java.util.stream.Collectors.toList());
        
        page.setRecords(filteredRecords);
        return ApiResponse.success(page);
    }
} 